<template>
  <div class="setting-container">
    <!-- 顶部导航 -->
    <div class="header">
      <div class="back-button" @click="goBack">
        <van-icon name="arrow-left" size="24" />
      </div>
      <h1 class="header-title">设置</h1>
    </div>

    <div class="settings-content">
      <!-- 账户设置 -->
      <div class="settings-section">
        <h2 class="section-title">账户设置</h2>
        <van-cell-group inset class="settings-card">
          <van-cell @click="showEditProfileDialog = true" class="settings-item">
            <template #icon>
              <van-icon name="user-o" class="item-icon blue-icon" />
            </template>
            <template #title>
              <span class="item-title">编辑资料</span>
            </template>
            <template #right-icon>
              <van-icon name="arrow" class="arrow-icon" />
            </template>
          </van-cell>
          
          <van-cell @click="goToTransactionPassword" class="settings-item">
            <template #icon>
              <van-icon name="lock" class="item-icon blue-icon" />
            </template>
            <template #title>
              <span class="item-title">交易密码</span>
            </template>
            <template #right-icon>
              <van-icon name="arrow" class="arrow-icon" />
            </template>
          </van-cell>
          
          <van-cell @click="goToShippingAddress" class="settings-item">
            <template #icon>
              <van-icon name="location-o" class="item-icon blue-icon" />
            </template>
            <template #title>
              <span class="item-title">收货地址</span>
            </template>
            <template #right-icon>
              <van-icon name="arrow" class="arrow-icon" />
            </template>
          </van-cell>
        </van-cell-group>
      </div>
      
      <!-- 通用设置 -->
      <div class="settings-section">
        <h2 class="section-title">通用设置</h2>
        <van-cell-group inset class="settings-card">
          <van-cell @click="goToNotifications" class="settings-item">
            <template #icon>
              <van-icon name="bell" class="item-icon blue-icon" />
            </template>
            <template #title>
              <span class="item-title">消息通知</span>
            </template>
            <template #right-icon>
              <van-icon name="arrow" class="arrow-icon" />
            </template>
          </van-cell>
          
          <van-cell @click="goToSecurityCenter" class="settings-item">
            <template #icon>
              <van-icon name="shield-o" class="item-icon blue-icon" />
            </template>
            <template #title>
              <span class="item-title">安全中心</span>
            </template>
            <template #right-icon>
              <van-icon name="arrow" class="arrow-icon" />
            </template>
          </van-cell>
          
          <van-cell @click="joinTelegramGroup" class="settings-item">
            <template #icon>
              <van-icon name="chat-o" class="item-icon blue-icon" />
            </template>
            <template #title>
              <span class="item-title">联系我们</span>
            </template>
            <template #right-icon>
              <div class="right-content">
                <span class="right-text">加入电报群</span>
                <van-icon name="arrow" class="arrow-icon" />
              </div>
            </template>
          </van-cell>
        </van-cell-group>
      </div>
      
      <!-- 法律与隐私 -->
      <div class="settings-section">
        <h2 class="section-title">法律与隐私</h2>
        <van-cell-group inset class="settings-card">
          <van-cell @click="goToPrivacyPolicy" class="settings-item">
            <template #icon>
              <van-icon name="description" class="item-icon blue-icon" />
            </template>
            <template #title>
              <span class="item-title">隐私政策</span>
            </template>
            <template #right-icon>
              <van-icon name="arrow" class="arrow-icon" />
            </template>
          </van-cell>
          
          <van-cell @click="goToUserAgreement" class="settings-item">
            <template #icon>
              <van-icon name="info-o" class="item-icon blue-icon" />
            </template>
            <template #title>
              <span class="item-title">用户协议</span>
            </template>
            <template #right-icon>
              <van-icon name="arrow" class="arrow-icon" />
            </template>
          </van-cell>
          
          <van-cell @click="goToAbout" class="settings-item">
            <template #icon>
              <van-icon name="question-o" class="item-icon blue-icon" />
            </template>
            <template #title>
              <span class="item-title">关于我们</span>
            </template>
            <template #right-icon>
              <van-icon name="arrow" class="arrow-icon" />
            </template>
          </van-cell>
        </van-cell-group>
      </div>
      
      <!-- 退出登录 -->
      <van-cell-group inset class="settings-card logout-card">
        <van-cell @click="showLogoutConfirm" class="logout-item">
          <template #title>
            <div class="logout-content">
              <van-icon name="close" class="logout-icon" />
              <span class="logout-text">退出登录</span>
            </div>
          </template>
        </van-cell>
      </van-cell-group>
    </div>

    <!-- 编辑资料弹窗 -->
    <van-dialog
      v-model:show="showEditProfileDialog"
      title="编辑资料"
      show-cancel-button
      confirm-button-text="保存"
      confirm-button-color="#1989fa"
      @confirm="saveProfile"
    >
      <div class="dialog-content">
        <div class="form-item">
          <div class="form-label">昵称</div>
          <van-field
            v-model="nickname"
            placeholder="请输入昵称"
            class="form-input"
          />
        </div>
        
        <div class="form-item" v-if="inviter === '' && inviterCode != '000000'">
          <div class="form-label">绑定邀请人</div>
          <van-field
            v-model="inviter"
            placeholder="请输入邀请人的邀请码"
            class="form-input"
          />
        </div>
      </div>
    </van-dialog>

    <!-- 退出登录确认弹窗 -->
    <van-dialog
      v-model:show="showLogoutConfirm"
      title="退出登录"
      show-cancel-button
      confirm-button-text="确认退出"
      confirm-button-color="#ee0a24"
      @confirm="logout"
    >
      <div class="dialog-content">
        <p>确定要退出登录吗？</p>
        <p class="dialog-subtitle">退出后需要重新登录才能使用完整功能。</p>
      </div>
    </van-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showLoadingToast, closeToast } from 'vant'
import { getUserProfile, updateUserProfile, logout as apiLogout } from '@/api/user'

const router = useRouter()
const showEditProfileDialog = ref(false)
const showLogoutConfirm = ref(false)
const nickname = ref('')
const inviter = ref('')
const inviterCode = ref('')
const loading = ref(false)

// 获取用户资料
const fetchUserProfile = async () => {
  loading.value = true
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
    duration: 0
  })
  
  try {
    const res = await getUserProfile()
    if (res && res.code === 0 && res.data) {
      nickname.value = res.data.nickname
      inviter.value = res.data.inviter
      inviterCode.value = res.data.inviteCode
    } else {
      showToast(res.message || '获取用户资料失败')
    }
  } catch (error) {
    console.error('获取用户资料出错:', error)
    showToast('获取用户资料出错')
  } finally {
    loading.value = false
    closeToast()
  }
}

// 初始化
onMounted(() => {
  fetchUserProfile()
})

// 导航方法
const goBack = () => {
  router.back()
}

const goToTransactionPassword = () => {
  router.push('/deal-pass')
}

const goToShippingAddress = () => {
  router.push('/address')
}

const goToPrivacyPolicy = () => {
  router.push('/agreement/privacy')
}

const goToUserAgreement = () => {
  router.push('/agreement/user')
}

const goToAbout = () => {
  router.push('/about')
}

const goToNotifications = () => {
  router.push('/notifications')
}

const goToSecurityCenter = () => {
  router.push('/security-center')
}

const joinTelegramGroup = () => {
  window.open('https://t.me/btdapp_official', '_blank')
}

// 保存资料
const saveProfile = async () => {
  if (!nickname.value) {
    showToast('请输入昵称')
    return
  }
  
  loading.value = true
  showLoadingToast({
    message: '保存中...',
    forbidClick: true,
    duration: 0
  })
  
  try {
    const res = await updateUserProfile({
      nickname: nickname.value,
      inviter: inviter.value
    })
    
    if (res.success) {
      showToast({
        message: '资料保存成功',
        icon: 'success'
      })
      showEditProfileDialog.value = false
    } else {
      showToast(res.message || '保存失败')
    }
  } catch (error) {
    console.error('保存资料出错:', error)
    showToast('保存资料出错')
  } finally {
    loading.value = false
    closeToast()
  }
}

// 退出登录
const showLogout = () => {
  showLogoutConfirm.value = true
}

const logout = async () => {
  loading.value = true
  showLoadingToast({
    message: '退出中...',
    forbidClick: true,
    duration: 0
  })
  
  try {
    const res = await apiLogout()
    if (res.success) {
      showToast({
        message: '已退出登录',
        icon: 'success'
      })
      
      // 清除本地存储的用户信息和token
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      
      // 跳转到登录页
      setTimeout(() => {
        router.push('/login')
      }, 500)
    } else {
      showToast(res.message || '退出登录失败')
    }
  } catch (error) {
    console.error('退出登录出错:', error)
    showToast('退出登录出错')
  } finally {
    loading.value = false
    closeToast()
  }
}
</script>

<style scoped>
.setting-container {
  min-height: 100vh;
  background-color: #f8fafc;
  padding-bottom: 24px;
}

/* 顶部导航 */
.header {
  display: flex;
  align-items: center;
  padding: 16px;
  margin-bottom: 16px;
}

.back-button {
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #334155;
  background: transparent;
  border: none;
  padding: 0;
}

.header-title {
  font-size: 20px;
  font-weight: 700;
  margin-left: 8px;
  color: #1e293b;
}

/* 设置内容 */
.settings-content {
  padding: 0 16px;
}

.settings-section {
  margin-bottom: 24px;
}

.section-title {
  font-size: 14px;
  font-weight: 500;
  color: #64748b;
  margin-bottom: 8px;
  padding-left: 4px;
}

.settings-card {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  background-color: white;
}

.settings-card :deep(.van-cell) {
  padding: 16px;
  align-items: center;
}

.settings-card :deep(.van-cell::after) {
  left: 16px;
  right: 16px;
  border-bottom: 1px solid #f1f5f9;
}

.settings-card :deep(.van-cell:last-child::after) {
  display: none;
}

.settings-item {
  transition: background-color 0.2s;
}

.settings-item:active {
  background-color: #f8fafc;
}

.item-icon {
  font-size: 20px;
  margin-right: 12px;
}

.blue-icon {
  color: #2563eb;
}

.item-title {
  font-size: 16px;
  color: #334155;
}

.arrow-icon {
  font-size: 16px;
  color: #94a3b8;
}

.right-content {
  display: flex;
  align-items: center;
}

.right-text {
  font-size: 14px;
  color: #94a3b8;
  margin-right: 4px;
}

/* 退出登录 */
.logout-card {
  margin-top: 32px;
}

.logout-item {
  transition: background-color 0.2s;
}

.logout-item:active {
  background-color: #fee2e2;
}

.logout-content {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
}

.logout-icon {
  font-size: 20px;
  color: #ef4444;
  margin-right: 8px;
}

.logout-text {
  font-size: 16px;
  font-weight: 500;
  color: #ef4444;
}

/* 弹窗样式 */
.dialog-content {
  padding: 16px;
}

.form-item {
  margin-bottom: 16px;
}

.form-label {
  font-size: 14px;
  font-weight: 500;
  color: #334155;
  margin-bottom: 8px;
}

.form-input {
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  overflow: hidden;
}

.form-input :deep(.van-field__control) {
  height: 40px;
}

.dialog-subtitle {
  font-size: 14px;
  color: #64748b;
  margin-top: 8px;
}
</style>